<?php


namespace frontend\models;

use common\models\PostsModel;
use common\models\RelationPostTagsModel;
use Yii;
use yii\base\Model;
use yii\db\Query;
use yii\web\NotFoundHttpException;

class PostsForm extends Model
{
    public $id;
    public $title;
    public $content;
    public $label_img;
    public $cat_id;
    public $tags;

    public $_lastError = "";
    /**
     * 定义场景
     * SCENARIO_CREATE 创建场景
     * SCENARIO_UPDATE 更新场景
     */
    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';
    /**
     * 定义事件
     * EVENT_AFTER_CREATE 创建后事件
     * EVENT_AFTER_UPDATE 更新后事件
     */
    const EVENT_AFTER_CREATE = 'eventAfterCreate';
    const EVENT_AFTER_UPDATE = 'eventAfterUpdate';

    /**
     * 场景设置
     * @return array|array[]
     */
    public function scenarios()
    {
        $scenarios = [
            self::SCENARIO_CREATE => ['title', 'content', 'label_img', 'cat_id', 'tags'],
            self::SCENARIO_UPDATE => ['title', 'content', 'label_img', 'cat_id', 'tags']
        ];
        return array_merge(parent::scenarios(), $scenarios); // TODO: Change the autogenerated stub
    }

    public function rules()
    {
        return [
            [['id', 'title', 'cat_id'], 'required'],
            [['id', 'cat_id'], 'integer'],
            ['title', 'string', 'min' => 4, 'max' => 50],
        ]; // TODO: Change the autogenerated stub
    }

    public function attributeLabels()
    {
        return [
            'id' => '编码',
            'title' => '标题',
            'content' => '内容',
            'label_img' => '标签图',
            'tags' => '标签',
            'cat_id' => '分类',
        ]; // TODO: Change the autogenerated stub
    }

    public static function getList($cond, $curPage = 1, $pageSize = 5, $orderBy = ['id' => SORT_DESC])
    {
        $model = new PostsModel();
        //查询语句
        $select = ['id', 'title', 'summary', 'label_img', 'cat_id', 'user_id', 'user_name', 'is_valid', 'created_at', 'updated_at'];
        $query = $model->find()->select($select)->where($cond)->with('relate.tag', 'extend')->orderBy($orderBy);
//        echo $query->createCommand()->getRawSql();die;
        //获取分页数据
        $res = $model->getPages($query, $curPage, $pageSize);
        //格式化数据
        $res = self::_fomatList($res);
        return $res;

    }

    /**
     * 数据格式化
     * @param $data
     */
    public static function _fomatList($data)
    {
        foreach ($data as &$list) {
            $tags = [];
            if (isset($list['relate']) && !empty($relate)) {
                foreach ($list['relate'] as $lt) {
                    $tags[] = $lt['tag']['tag_name'];
                }
                $list['tags'] = $tags;
//                unset($list['relate']);
            }
        }
        return $data;
    }

    /**
     * 文章创建
     * @return bool
     */
    public function create()
    {
        //事务
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = new PostsModel();
            $model->setAttributes($this->attributes);
            $model->summary = $this->_getSummary();
            $model->user_id = Yii::$app->user->identity->id;
            $model->user_name = Yii::$app->user->identity->username;
            $model->is_valid = PostsModel::IS_VALID;
            $model->created_at = time();
            $model->updated_at = time();
            if (!$model->save()) {
                throw new \Exception('文章保存失败');
            }
            $this->id = $model->id;

            //创建后的调用事件
            $data = array_merge($this->getAttributes(), $model->getAttributes());
            $this->_eventAfterCreate($data);
            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->_lastError = $e->getMessage();
            return false;

        }
    }

    /**
     * 文章编辑
     * @return bool
     */
    public function edit($id)
    {
        if(!($this->isEditShow(yii::$app->user->identity->getId(),$id))){
            throw new \Exception('你没有编辑权限！');
        }
        //事务
        $transaction = \Yii::$app->db->beginTransaction();
        try {
//            $model = PostsModel::find()->where(['id'=>$id])->one();
//            var_dump($this->attributes);die;
            $model = PostsModel::findOne($id);
//            $model = new PostsModel();
            $model->setAttributes($this->attributes);
            $model->summary = $this->_getSummary();
//            $model->user_id = Yii::$app->user->identity->id;
//            $model->user_name = Yii::$app->user->identity->username;
            $model->is_valid = PostsModel::IS_VALID;
//            $model->created_at = time();
            $model->updated_at = time();

            if (!$model->save()) {
                throw new \Exception('文章编辑失败');
            }
            $this->id = $model->id;

            //创建后的调用事件
            $data = array_merge($this->getAttributes(), $model->getAttributes());
            $this->_eventAfterEdit($data);
            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->_lastError = $e->getMessage();
            return false;

        }
    }

    public function getItem($id)
    {
        $res = $this->getViewById($id);

        return $res;
    }

    public function getViewById($id)
    {
        $res = PostsModel::find()->with('relate.tag', 'extend')->where(['id' => $id])->asArray()->one();
        if (!$res) {
            throw new NotFoundHttpException('文章页面不存在');
        }
        //处理标签格式
        $res['tags'] = [];
        if (isset($res['relate']) && !empty($res['relate'])) {
            foreach ($res['relate'] as $list) {
                $res['tags'][] = $list['tag']['tag_name'];
            }
        }

        unset($res['relate']);
//        print_r($res);
        return $res;
    }
    public function isEditShow($user_id,$id){
        // 是否显示编辑按钮，是自己创建的文章则显示，否则不显示
        $count = PostsModel::find()->where(['user_id' => $user_id, 'is_valid' => 1,'id'=>$id])->count('id');
        return $count>0?1:0;
    }
    public function getMylistDateArr($user_id)
    {
        $sql = "SELECT FROM_UNIXTIME(created_at, '%Y-%m-%d') time,FROM_UNIXTIME(created_at, '%Y年%m月%d') datestring FROM `posts` WHERE user_id={$user_id} GROUP BY FROM_UNIXTIME(created_at, '%Y-%m-%d')  order by time desc limit 10";
        $datearr = Yii::$app->getDb()->createCommand($sql)->queryAll();
        return $datearr ?: [];
    }

    public function getMyPostCount($user_id)
    {
        $data = [];
        $sql = "select sum(t2.browser) as  browserCount from posts t1 left join post_extends t2 on t1.id=t2.post_id where t1.user_id={$user_id} and t1.is_valid=1";
        $browserCount = Yii::$app->getDb()->createCommand($sql)->queryAll();
        $postsCount = PostsModel::find()->where(['user_id' => $user_id, 'is_valid' => 1])->count('id');
        $data = [
            'browser_count' =>$browserCount[0]['browserCount'],
            'posts_count' =>$postsCount,
        ];
        return $data ?: [];
    }

    /**
     * 截取文章摘要
     * @param int $s
     * @param int $e
     * @param string $char
     * @return string|null
     */
    private function _getSummary($s = 0, $e = 90, $char = 'utf-8')
    {
        if (empty($this->content)) {
            return null;
        }
        return mb_substr(str_replace('&nbsp;', '', strip_tags($this->content)), $s, $e, $char);

    }

    /**
     * 创建完成后调用事件方法
     */
    public function _eventAfterCreate($data)
    {
        //添加事件
        $this->on(self::EVENT_AFTER_CREATE, [$this, '_eventAddTag'], $data);
        //触发事件
        $this->trigger(self::EVENT_AFTER_CREATE);
    }

    /**
     * 编辑完成后调用事件方法
     */
    public function _eventAfterEdit($data)
    {
        //添加事件
        $this->on(self::EVENT_AFTER_UPDATE, [$this, '_eventAddTag'], $data);
        //触发事件
        $this->trigger(self::EVENT_AFTER_UPDATE);
    }

    /**
     * 添加标签
     */
    public function _eventAddTag($event)
    {
        //保存标签
        $tag = new TagForm();
        $tag->tags = $event->data['tags'];
        $tagids = $tag->saveTags();

        //删除原先的关联关系
        RelationPostTagsModel::deleteAll(['post_id' => $event->data['id']]);
        //批量保存文章和标签关系
        $row = [];
        if (!empty($tagids)) {
            foreach ($tagids as $k => $v) {
                $row[$k]['post_id'] = $this->id;
                $row[$k]['tag_id'] = $v;
            }
            $res = (new Query())->createCommand()->batchInsert(RelationPostTagsModel::tableName(), ['post_id', 'tag_id'], $row)->execute();
            if (!$res) {
                throw new \Exception('关联关系保存失败');
            }
        }
    }


}